<template>
  <div class="forum_manage">
    <!-- 板块管理 -->
    <el-tabs v-model="activeTab">
      <el-tab-pane label="板块管理" name="board">
        <el-row style="margin-bottom: 8px;">
          <el-col>
            <el-button type="danger" icon="delete" @click="deleteBoards" :disabled="selectedBoards.length === 0">批量删除</el-button>
            <el-button type="success" icon="plus" @click="openBoardDialog">新增板块</el-button>
            <el-button type="primary" icon="refresh" @click="reload">刷新</el-button>
          </el-col>
        </el-row>

        <el-table :data="boardList" border @selection-change="handleBoardSelection">
          <el-table-column type="selection" width="55"/>
          <el-table-column label="板块名称" prop="name"/>
          <el-table-column label="访问权限" prop="permission"/>
          <el-table-column label="主题数" prop="topic_count"/>
          <el-table-column label="回复数" prop="reply_count"/>
          <el-table-column label="操作" width="200" align="center">
            <template #default="{row}">
              <el-button size="small" @click="editBoard(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteBoard(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 主题管理 -->
      <el-tab-pane label="主题管理" name="topic">
        <el-table :data="topicList" border>
          <el-table-column label="标题" prop="title"/>
          <el-table-column label="作者" prop="author.username"/>
          <el-table-column label="板块" prop="board_name"/>
          <el-table-column label="状态" width="120">
            <template #default="{row}">
              <el-tag v-if="row.is_pinned" type="warning">置顶</el-tag>
              <el-tag v-if="row.is_essence" type="success">精华</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" align="center">
            <template #default="{row}">
              <el-button size="small" @click="togglePin(row)">{{ row.is_pinned ? '取消置顶' : '置顶' }}</el-button>
              <el-button type="success" size="small" @click="toggleEssence(row)">{{ row.is_essence ? '取消精华' : '设精华' }}</el-button>
              <el-button type="danger" size="small" @click="deleteTopic(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="topicTotal"
            @current-change="handleTopicPageChange"
          />
        </div>
      </el-tab-pane>
      <!-- 回复管理 -->
        <el-tab-pane label="回复管理" name="reply">
            <el-table :data="replyList" border style="width: 100%">
                <el-table-column label="内容" prop="content" show-overflow-tooltip/>
                <el-table-column label="作者" prop="author.username" width="120"/>
                <el-table-column label="所属主题" prop="topic.title" width="200" show-overflow-tooltip/>
                <el-table-column label="点赞数" prop="like_count" width="80"/>
                <el-table-column label="操作" width="120" align="center">
                <template #default="{row}">
                    <el-button type="danger" size="small" @click="deleteReply(row.id)">删除</el-button>
                </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                background
                layout="prev, pager, next"
                :total="replyTotal"
                @current-change="handleReplyPageChange"
                />
            </div>
        </el-tab-pane>
    </el-tabs>


    <!-- 板块编辑对话框 -->
    <el-dialog :title="boardForm.id ? '编辑板块' : '新增板块'" v-model="boardDialogVisible">
      <el-form :model="boardForm" :rules="boardRules" label-width="100px">
        <el-form-item label="板块名称" prop="name">
          <el-input v-model="boardForm.name"/>
        </el-form-item>
        <el-form-item label="访问权限" prop="permission">
          <el-select v-model="boardForm.permission">
            <el-option label="公开" value="public"/>
            <el-option label="注册用户" value="registered"/>
            <el-option label="私有" value="private"/>
          </el-select>
        </el-form-item>
        <el-form-item label="版主" prop="moderator">
          <el-select v-model="boardForm.moderator" filterable remote :remote-method="searchUser">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="boardForm.description" type="textarea" rows="4"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="boardDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBoard">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
	board_list,
	board_create,
	board_update,
	board_delete,
	topic_list,
	topic_pin,
	topic_essence,
	reply_list,
	reply_delete,
	user_search, del_topic
} from '/@/api/forum'

const activeTab = ref('board')

// 回复相关状态
const replyList = ref([])
const replyTotal = ref(0)
const replyQuery = reactive({
  page: 1,
  page_size: 10,
  topic_id: null,
  author_id: null
})

// 加载回复数据
const loadReplies = async () => {
  const res = await reply_list(replyQuery)
  replyList.value = res.data.replies
  replyTotal.value = res.data.total
}

// 删除回复
const deleteReply = async (id) => {
  await ElMessageBox.confirm('确认删除该回复？', '警告', { type: 'warning' })
  await reply_delete(id)
  ElMessage.success('删除成功')
  loadReplies()
}

// 回复分页处理
const handleReplyPageChange = (currentPage) => {
  replyQuery.page = currentPage
  loadReplies()
}

// 板块相关状态
const boardList = ref([])
const selectedBoards = ref([])
const boardDialogVisible = ref(false)
const boardForm = reactive({
  id: null,
  name: '',
  permission: 'public',
  description: '',
  moderator: null
})

// 主题相关状态
const topicList = ref([])
const topicTotal = ref(0)
const topicQuery = reactive({
  page: 1,
  page_size: 10,
  is_essence: null,
  is_pinned: null
})

// 用户搜索
const userList = ref([])

// 表单验证规则
const boardRules = reactive({
  name: [{ required: true, message: '请输入板块名称', trigger: 'blur' }],
  permission: [{ required: true, message: '请选择访问权限', trigger: 'change' }]
})

// 初始化加载数据
onMounted(() => {
  loadBoards()
  loadTopics()
  loadReplies()
})

// 加载板块数据
const loadBoards = async () => {
  const res = await board_list()
  boardList.value = res.data.boards
}

// 加载主题数据
const loadTopics = async () => {
  const res = await topic_list(topicQuery)
  topicList.value = res.data.topics
  topicTotal.value = res.data.total
}

// 保存板块
const saveBoard = async () => {
  try {
    if (boardForm.id) {
      await board_update(boardForm.id, boardForm)
    } else {
      await board_create(boardForm)
    }
    ElMessage.success('保存成功')
    boardDialogVisible.value = false
    loadBoards()
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 删除板块
const deleteBoard = async (id) => {
  await ElMessageBox.confirm('确认删除该板块?', '警告', { type: 'warning' })
  await board_delete(id)
  ElMessage.success('删除成功')
	topicQuery.value = 1
	topicQuery.is_essence = null
	topicQuery.is_pinned = null
 	loadBoards()
}

// 主题置顶/取消置顶
const togglePin = async (topic) => {
  await topic_pin(topic.id)
  topic.is_pinned = !topic.is_pinned
  ElMessage.success(topic.is_pinned ? '已置顶' : '已取消置顶')
}

// 主题设置精华/取消精华
const toggleEssence = async (topic) => {
  await topic_essence(topic.id)
  topic.is_essence = !topic.is_essence
  ElMessage.success(topic.is_essence ? '已设为精华' : '已取消精华')
}
//删除主题
const deleteTopic = async (topic)=>{
	const confirm = await ElMessageBox.confirm('确认删除该主题？', '警告', { type: 'warning' })
	await del_topic(topic.id)
	ElMessage.success('删除成功！')
	await loadTopics()
}

// 用户搜索
const searchUser = async (query) => {
  if (query) {
    const res = await user_search({ username: query })
    userList.value = res.data.list
  }
}

// 在script setup部分添加以下方法
const openBoardDialog = () => {
  boardForm.id = null
  boardForm.name = ''
  boardForm.permission = 'public'
  boardForm.description = ''
  boardForm.moderator = null
  userList.value = [] // 清空用户搜索结果
  boardDialogVisible.value = true
}

// 补充处理分页变化的方法
const handleTopicPageChange = (currentPage) => {
  topicQuery.page = currentPage
  loadTopics()
}

// 补充处理批量选择的方法
const handleBoardSelection = (selection) => {
  selectedBoards.value = selection.map(item => item.id)
}

// 补充批量删除方法
const deleteBoards = async () => {
  await ElMessageBox.confirm('确认删除选中板块？', '警告', { type: 'warning' })
  await Promise.all(selectedBoards.value.map(id => board_delete(id)))
  ElMessage.success('批量删除成功')
  loadBoards()
}

// 补充编辑板块方法
const editBoard = (row) => {
  boardForm.id = row.id
  boardForm.name = row.name
  boardForm.permission = row.permission
  boardForm.description = row.description
  boardForm.moderator = row.moderator?.id || null
  boardDialogVisible.value = true
}

// 补充刷新方法
const reload = () => {
  loadBoards()
  loadTopics()
  loadReplies()
}

</script>

<style scoped>
.forum_manage {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
